package kotan.view.table;

import java.awt.Color;
import java.awt.Component;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;

import kotan.KotanConstants;
import kotan.datastore.api.Key;

/**
 * CellRenderer for EntityViewer.
 * @author shuji.w6e
 * @since 1.0
 */
public class EntityCellRenderer extends DefaultTableCellRenderer implements TableCellRenderer {
    private static final long serialVersionUID = 1L;
    private Color defaultForeground;
    private Color nullForeground = new Color(70, 70, 70);
    private Color defaultBackground;
    private Color hilightBackground = new Color(230, 230, 255);

    /**
     * Constructor.
     */
    public EntityCellRenderer() {
        defaultBackground = getBackground();
        defaultBackground = getForeground();
    }

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
            int row, int column) {
        // Foreground
        if (value == null) { // null value.
            super.setForeground(nullForeground);
        } else {
            super.setForeground(defaultForeground);
        }
        // Background
        if (!isSelected && row % 2 == 1) {
            super.setBackground(hilightBackground);
        } else {
            super.setBackground(defaultBackground);
        }
        // null value
        if (value == null) {
            value = ( 0 < column) ? "(null)" : "<Enter to create a new entity>";
        } else {
            Class<?> clazz = value.getClass();
            if (clazz == Date.class) {
                value = new SimpleDateFormat(KotanConstants.DEFAULT_DATE_FORMAT).format(value);
            } else if (clazz == Key.class) {
                Key key = (Key) value;
                if (0 < key.getId()) {
                    value = "id=" + key.getId();
                } else {
                    value = "name=" + key.getName();
                }
            }
        }
        return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
    }

    @Override
    public void setForeground(Color c) {
        super.setForeground(c);
        this.defaultForeground = c;
    }

    @Override
    public void setBackground(Color c) {
        super.setBackground(c);
        this.defaultBackground = c;
    }
}
